package apis

import (
	"xiaoercaidan/baseApi/dao"
	"xiaoercaidan/publicResources/controller"
	"xiaoercaidan/publicResources/models"
	"time"
	"encoding/json"
	"fmt"
	"xiaoercaidan/publicResources/utils"
	"github.com/goinggo/mapstructure"
	"github.com/astaxie/beego"
	"strconv"
)

type UserApi struct {
	controller.BaseController
}

// @Title Login
// @Description 会员登录
// @Param   userName     patch string   true int64       "用户名"
// @Param   passWord    patch string  true  string       "密码"
// @Success 200 {object} models.User
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /login [get]
func (c *UserApi) Login() {

	var name = ""
	var passWord = ""

	c.Ctx.Input.Bind(&name, "userName")
	c.Ctx.Input.Bind(&passWord, "passWord")

	var params = make(map[string]string)

	params["user_name"] = name
	params["pass_word"] = passWord

	user := dao.QeryUser(params)

	var BaseResult = new(models.BaseResult)

	if (user != nil &&user.Id > 0) {

		user.BaiduToken = beego.AppConfig.String("baiduToken")

		user.Token = dao.QueryOrCreateUserToken(user.Id)

		BaseResult.Data = user
	} else {
		BaseResult.Code = 101
		BaseResult.Msg = "登录失败，用户名或则密码不匹配"
	}

	c.Data["json"] = &BaseResult
	c.ServeJSON()

}


// @Title GetUserToken
// @Description 获取用户token
// @Param   userId     patch int64   true int64       "用户ID"
// @router /getUserToken [get]
func (c *UserApi) GetUserToken() {

	var BaseResult = new(models.BaseResult)

	userId, _ := c.GetInt64("userId", 0)

	if (userId <= 0  ) {
		BaseResult.Code = 100
		BaseResult.Msg = "参数不全"
	} else {

		userToken := dao.QueryUserToken(userId)

		if (userToken == nil) {

			BaseResult.Code = 100
			BaseResult.Msg = "用户信息异常"

		} else {
			BaseResult.Data = userToken
		}

	}

	c.Data["json"] = &BaseResult
	c.ServeJSON()
}



// @Title UserTokenVeri
// @Description 用户token验证
// @Param   userId     patch int64   true int64       "用户ID"
// @Param   token     patch string   true string       "token"
// @Param   timeStamp     patch int64   true int64       "时间戳"
// @router /userTokenVeri [get]
func (c *UserApi) UserTokenVeri() {

	var BaseResult = new(models.BaseResult)

	userId, _ := c.GetInt64("userId", 0)

	timeStamp, _ := c.GetInt64("timeStamp", 0)

	token := c.GetString("token")

	if (userId <= 0 || timeStamp <= 0 || len(token) <= 0 ) {
		BaseResult.Code = 100
		BaseResult.Msg = "参数不全"
	} else {

		userToken := dao.QueryUserToken(userId)

		if (userToken == nil) {

			BaseResult.Code = 100
			BaseResult.Msg = "用户信息异常"

		} else {
			tokenStr := utils.Md5(strconv.FormatInt(userId, 10) + beego.AppConfig.String("privateKey") + userToken.Token + beego.AppConfig.String("privateKey") + strconv.FormatInt(timeStamp, 10))

			fmt.Println(token)
			fmt.Println(tokenStr)

			if (token != tokenStr) {
				BaseResult.Code = 100
				BaseResult.Msg = "身份验证不通过,请求非法"
			} else {
				BaseResult.Code = 0
				BaseResult.Msg = "身份验证通过,请求合法"
			}
		}

	}

	c.Data["json"] = &BaseResult
	c.ServeJSON()
}




// @Title Login
// @Description 会员登录
// @Param   name     patch string   true int64       "用户名"
// @router /userUnique [get]
func (c *UserApi) UserUnique() {

	var BaseResult = new(models.BaseResult)

	var name = c.GetString("name")

	if &name == nil || len(name) <= 0 {
		BaseResult.Code = 100
		BaseResult.Msg = "参数不能为空"
	} else {

		var params = make(map[string]string)
		params["user_name"] = name
		user := dao.QeryUser(params)
		if (user != nil && user.Id > 0) {
			BaseResult.Code = 101
			BaseResult.Msg = "用户已存在"
		}
	}

	c.Data["json"] = &BaseResult
	c.ServeJSON()

}


// @Title Regist
// @Description 会员注册
// @Param   user     patch string   true string       "用户json"
// @Success 200 {object} models.User
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /regist  [get]
func (c *UserApi) Regist() {

	var BaseResult = new(models.BaseResult)

	var userStr = c.GetString("user")

	if ( len(userStr) <= 0) {
		BaseResult.Code = 100
		BaseResult.Msg = "参数为空"
	} else {

		var mapStr map[string]interface{}

		json.Unmarshal([]byte(userStr), &mapStr)

		for k := range mapStr {
			if k == "Id" {
				mapStr[k] = nil
			}

		}

		user := new(models.User)
		user.Role = new(models.Role)

		mapstructure.Decode(mapStr, user);
		mapstructure.Decode(mapStr["Role"], user.Role);

		user.CreateTime = time.Now().UTC().Unix()

		err := dao.InserUser(user)

		if (utils.CheckResult(BaseResult, err)) {
			BaseResult.Data = user
		}

	}

	c.Data["json"] = &BaseResult
	c.ServeJSON()

}


// @Title RoleAdd
// @Description 新增角色
// @Param   role     patch string   true string       "角色json"
// @Success 200 {object} models.Role
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /roleAdd  [get]
func (c *UserApi) RoleAdd() {

	var BaseResult = new(models.BaseResult)

	var roleStr = c.GetString("role")

	if ( len(roleStr) <= 0) {
		BaseResult.Code = 100
		BaseResult.Msg = "参数为空"
	} else {

		var mapStr map[string]interface{}

		json.Unmarshal([]byte(roleStr), &mapStr)

		for k := range mapStr {
			if k == "Id" {
				mapStr[k] = nil
			}
		}

		var role = new(models.Role)

		if err := mapstructure.Decode(mapStr, role); err != nil {

			BaseResult.Msg = err.Error()
			BaseResult.Code = 100

		} else {
			err := dao.InserRole(role)
			if (utils.CheckResult(BaseResult, err)) {
				BaseResult.Data = role
			}
		}

	}

	c.Data["json"] = &BaseResult
	c.ServeJSON()
}



// @Title RoleList
// @Description 获取角色列表
// @Success 200 {object} models.Role
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /roleList  [get]
func (this *UserApi) RoleList() {

	role := dao.QeryRole()

	if role == nil {
		role = new([]models.Role)
	}

	var BaseResult = new(models.BaseResult)
	BaseResult.Data = role

	this.Data["json"] = &BaseResult

	this.ServeJSON()
}


// @Title UserList
// @Description 获取用户列表
// @Param   id    patch string  true  string       "Id"
// @Param   name    patch string  true  string       "用户名"
// @Param   phone    patch string  true  string       "电话号码"
// @Success 200 {object} models.User
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /userList  [get]
func (this *UserApi) UserList() {

	var params = make(map[string]string)

	if this.GetString("id") != "" {
		params["id"] = this.GetString("id", "")
	}

	if this.GetString("name") != "" {
		params["user_name"] = this.GetString("name", "")
	}

	if this.GetString("phone") != "" {
		params["phone"] = this.GetString("phone", "")
	}

	users := dao.QeryUserBlur(params)

	var BaseResult = new(models.BaseResult)

	BaseResult.Data = users

	this.Data["json"] = BaseResult

	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	this.Ctx.ResponseWriter.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
	this.Ctx.ResponseWriter.Header().Set("content-type", "application/json")             //返回数据格式是json

	this.ServeJSON()
}

// @Title UserDel
// @Description 删除用户
// @Param   ids    patch string  true  string       "要删除的Id列表，用“,”分割"
// @Success 200 {object} models.User
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /userDel [get]
func (this *UserApi) UserDel() {

	var BaseResult = new(models.BaseResult)

	ids := this.GetString("ids")

	if ( len(ids) <= 0) {
		BaseResult.Code = 100
		BaseResult.Msg = "参数为空"
	} else {
		err := dao.DeleteUsers(ids)
		if (err != nil) {
			BaseResult.Code = 100
			BaseResult.Msg = err.Error()
		} else {
			BaseResult.Msg = "删除成功"
		}
	}

	this.Data["json"] = &BaseResult
	this.ServeJSON()

}



// @Title UserUpdate
// @Description 修改用户信息
// @Param  user   patch models.User  true  string       用户数据
// @Success 200 {object} models.User
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /userUpdate [get]
func (this *UserApi) UserUpdate() {

	var BaseResult = new(models.BaseResult)

	var user = new(models.User)

	var userJson = ""
	this.Ctx.Input.Bind(&userJson, "user")

	if ( len(userJson) <= 0) {
		BaseResult.Code = 100
		BaseResult.Msg = "参数为空"

	} else {

		//var mapStr map[string]interface{}

		json.Unmarshal([]byte(userJson), &user)

		fmt.Println(userJson)
		fmt.Println(user)

		err := dao.UpdateUser(user)

		if (utils.CheckResult(BaseResult, err)) {
			BaseResult.Data = user
		}

	}

	this.Data["json"] = &BaseResult
	this.ServeJSON()
}


